/**
 * Copyright millionhere
 * Licensed under the Apache License, Version 2.0 (the "License");
 * You may see it at...
 *      http://www.apache.org/licenses/LICENSE-2.0
 */

package info.millionhere.keepsilent;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.HashMap;

import org.xmlpull.v1.XmlSerializer;

import android.os.Environment;
import android.sax.Element;
import android.sax.EndElementListener;
import android.sax.EndTextElementListener;
import android.sax.RootElement;
import android.util.Log;
import android.util.Xml;

public class BlackListXmlAdaptor {
    
    static final String TAG_ROOT = "blacklist";
    static final String TAG_ITEM = "rule";
    
    private static final String BLACKLIST_PATH = "/KeepSilent/";
    private static final String BLACKLIST_NAME = "/blacklist.xml";
    
    HashMap<String, BlackListElement> BlackList = new HashMap<String, BlackListElement>();
    String sAddress;
    String sComment;
    boolean bAvailable;
    
    public HashMap<String, BlackListElement> Read(){

	RootElement root = new RootElement("", TAG_ROOT);
	Element item = root.getChild("", TAG_ITEM);

	//When the end of a item
	item.setEndElementListener(new EndElementListener() {	
	    public void end() {
		BlackList.put(sAddress, new BlackListElement(sAddress, sComment, bAvailable));
	    }
	});

	//Handle TAG_ADDRESS
	item.getChild("", BlackListElement.TAG_ADDRESS).setEndTextElementListener(new EndTextElementListener() {
	    public void end(String currentData) {
		sAddress = currentData;
	    }
	});
	//Handle TAG_COMMENT
	item.getChild("", BlackListElement.TAG_COMMENT).setEndTextElementListener(new EndTextElementListener() {
	    public void end(String currentData) {
		sComment = currentData;
	    }
	});
	//Handle TAG_AVAILABLE
	item.getChild("", BlackListElement.TAG_AVAILABLE).setEndTextElementListener(new EndTextElementListener() {
	    public void end(String currentData) {
		bAvailable = (currentData.equalsIgnoreCase("true"))?true:false;
	    }
	});

	try{
	    FileInputStream fis = new FileInputStream(Environment.getExternalStorageDirectory() + BLACKLIST_PATH + BLACKLIST_NAME);
	    Xml.parse(fis, Xml.Encoding.UTF_8, root.getContentHandler());
	} catch (Exception e) {
	    Log.e("READ", "Read BlackList XML Failed");
	}
	
	return BlackList;
    }
    
    public String Write(ArrayList<BlackListElement> blackList){
	XmlSerializer serializer = Xml.newSerializer();
	StringWriter writer = new StringWriter();
	
	try{
	    serializer.setOutput(writer);

	    serializer.startDocument("UTF-8", true);

	    serializer.startTag("", TAG_ROOT);

	    for(BlackListElement rule:blackList){
	    writeOneRule(rule, serializer);
	    }
	    
	    serializer.endTag("", TAG_ROOT);

	    serializer.endDocument();
	    
	    confirmAppFolder();
	    
	    FileWriter fw = new FileWriter(Environment.getExternalStorageDirectory() + BLACKLIST_PATH + BLACKLIST_NAME);
	    fw.write(writer.toString());
	    fw.close();
	}
	catch(Exception e)
	{
	    return e.getMessage();
	}
	return writer.toString();
    }
    
    private void writeOneRule(BlackListElement rule, XmlSerializer serializer){
	try {
	serializer.startTag("", TAG_ITEM);
	ArrayList<String[]> ruleText = rule.Print();
	for(String[] sec:ruleText){
            serializer.startTag("", sec[0]);
	    serializer.text(sec[1]);
	    serializer.endTag("", sec[0]);
        }
	serializer.endTag("", TAG_ITEM);
	}
	catch (Exception e){
	    throw new RuntimeException(e);
	}
    }
    
    private int confirmAppFolder(){
	File path = new File(Environment.getExternalStorageDirectory() + BLACKLIST_PATH);
	if (!path.exists())
	    path.mkdirs();
	return 0;
    }
}
